/**
 * Projecte
 * @version 1.0  201203120916
 * @author jferrert@copernic.cat 12/03/2012
 * @copyright Creative commons (by-nc-nd) Reconeixement - NoComercial - CompartirIgual 
 */

/**
 * Ús :
 * ai = new AJAXInteraction("xyz.html",funcioResposta)
 * ai.doGet();
 */
function AJAXInteraction(url, callback) {

    var req = AJAXInteraction();
    req.onreadystatechange = processRequest;

    function AJAXInteraction() {
		var ajaxs = ["Msxml2.XMLHTTP","Msxml2.XMLHTTP.4.0","Msxml2.XMLHTTP.5.0","Msxml2.XMLHTTP.3.0","Microsoft.XMLHTTP"];
		var objReq = false;
		for(var i = 0 ; !objReq && i < ajaxs.length; i++){
			try{ 
				objReq = new ActiveXObject(ajaxs[i]); 
			}  catch(e) { 
				objReq = false; 
			}
		}
		if(!objReq && typeof XMLHttpRequest != 'undefined') {
			objReq = new XMLHttpRequest();
		}
		return objReq;
	}

    function processRequest() {
        if (req.readyState == 4) {
            if (req.status == 200) {
                if (callback) callback();
                else alert('no hi ha funcio'); 
            }
        }
    }

    this.doGet = function() {
        req.open("GET", url, true);  // async
        req.send(null);
    }

    this.doGetSync = function() {
        req.open("GET", url, false);  // sync
        req.send(null);
    }

    this.doPost = function(body) {
        req.open("POST", url, true);
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(body);
    }

    this.doPostSync = function(body) {
        req.open("POST", url, false);
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(body);
    }

    this.getResponseText = function()  {
        return req.responseText;  
    }

    this.getResponseXML = function()  {
        return req.responseXML;  
    }

    this.getResponseJSON = function()  {
        return eval('(' + req.responseText + ')');
    }
}

/**
 * Demana dades AJAX
 */
function getData(url, capaId, formId){
	var ajax;
	
	function carrega(){
		var scripts = ajax.getResponseText().extractScript();
		if(capaId) document.getElementById(capaId).innerHTML = ajax.getResponseText();
		scripts.evalScript();
	}

	ajax = new AJAXInteraction(url, carrega);
	if(!ajax){
		document.getElementById("error").innerHTML = "Error : El vostre navegador, no permet l'ús de totes les característiques d'aquesta aplicació!";
		return false;
	} else {
		if(!formId) ajax.doGet();	
		else ajax.doPost(serialize(formId));
	}
}

/**
 * Envia una form
 */

/**
 * Per fer submits vía Ajax d'un formulari (Sense refrescar la pàgina):
 */
function formData2QueryString(formId) {
    var docForm = document.getElementById(formId);
    var strSubmitContent = '';
    var formElem;
    var strLastElemName = '';

    for (i = 0; i < docForm.elements.length; i++) {
        formElem = docForm.elements[i];
        switch (formElem.type) {  // Text fields, hidden form elements
            case 'text':
            case 'hidden':
            //case 'file':
            case 'password':
            //case 'textarea':
            case 'select-one':
                strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
                break;
            case 'radio': // Radio buttons
                if (formElem.checked) {
                    strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
                }
                break;
			case 'checkbox':
				 if (formElem.checked) {
                    strSubmitContent += formElem.name + '=1&';					
				} else {
					strSubmitContent += formElem.name + '=0&';					
				}						
				break;
/*            case 'checkbox': // Checkboxes
                if (formElem.checked) {  
                    if (formElem.name == strLastElemName) {   // Continuing multiple, same-name checkboxes
                        if (strSubmitContent.lastIndexOf('&') == strSubmitContent.length-1) { // Strip of end ampersand if there is one
                            strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
                        }
                        strSubmitContent += ',' + escape(formElem.value); // Append value as comma-delimited string
                    } else {
                        strSubmitContent += formElem.name + '=' + escape(formElem.value);
                    }
                    strSubmitContent += '&';
                    strLastElemName = formElem.name;
                }
                break;  */
            case 'textarea':
				if(tinyMCE_Save){      // Per utilitzar amb editors javascript p.e. tinyMCE 
					strSubmitContent += formElem.name + '=' + escape(tinyMCE_Save(formElem.id)) + '&';
				} else {
					strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&';
				}
                break;
        }
    }
    // Remove trailing separator
    strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
    //alert(strSubmitContent);
    return strSubmitContent;
}


function serialize(formId) {
	var form = document.getElementById(formId); 
	if (!form || form.nodeName !== "FORM") {
		return;
	}
	var i, j, q = [];
	for (i = 0 ; i < form.elements.length; i++) {
		if (form.elements[i].name === "") {
			continue;
		}
		switch (form.elements[i].nodeName) {
		case 'INPUT':
			switch (form.elements[i].type) {
				case 'text':
				case 'hidden':
				case 'password':
				case 'button':
				case 'reset':
				case 'submit':
					q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
					break;
				case 'checkbox':
					if (form.elements[i].checked) {
						q.push(form.elements[i].name + "=1");
					} else  {
						q.push(form.elements[i].name + "=0");
					}						
					break;
				case 'radio':
					if (form.elements[i].checked) {
						q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
					}						
					break;
				case 'file':
					break;
			}
			break;			 
		case 'TEXTAREA':
				if(tinyMCE_Save){      // Per utilitzar amb editors javascript p.e. tinyMCE 
					q.push(form.elements[i].name + "=" + encodeURIComponent(tinyMCE_Save(form.elements[i].id)));
				} else {
					q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
				}
                break;
 		case 'SELECT':
			switch (form.elements[i].type) {
			case 'select-one':
				q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
				break;
			case 'select-multiple':
				for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
					if (form.elements[i].options[j].selected) {
						q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
					}
				}
				break;
			}
			break;
		case 'BUTTON':
			switch (form.elements[i].type) {
			case 'reset':
			case 'submit':
			case 'button':
				q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
				break;
			}
			break;
		}
	}
	//alert(q.join("&"));
	return q.join("&");
}

/**********************  Executar javascrips encastats en Ajax *****************/

/**
 * Expressió regular per determinar si un String que contè XHTML es un script. 
 */
 var tagScript = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';

/**
* Eval script fragment
* @return String
* *******************************
*  Executa els scripts encastats a un String que contè XHTML.
*  Retorna cert o fals si els ha executat.
*  Primer els extreu a un Array i executa Array.evalScript()
*/
String.prototype.evalScript = function() {
	return (this.match(new RegExp(tagScript, 'img')) || []).evalScript();
}

/**
* strip script fragment
* @return String
* *******************************
*  Elimina es scripts encastats en un String que contè XHTML
*  Retorna l'String XHTML sense els scripts
*/
String.prototype.stripScript = function() {
	return this.replace(new RegExp(tagScript, 'img'), '');
}

/**
* extract script fragment
* @return String
** *******************************
*  Extreu els scripts encastat en un String que contè XHTML
*  Retorna un Array amb els scripts
*/
String.prototype.extractScript = function() {
	var matchAll = new RegExp(tagScript, 'img');
	return (this.match(matchAll) || []);
}

/**
* Eval scripts
* @return String
* **********************
* Executa un Array d'scripts
*/
Array.prototype.evalScript = function(extracted) {
	var s = this.map(
        function(sr){
            var sc = (sr.match(new RegExp(tagScript, 'im')) || ['', ''])[1];
            if(window.execScript){
                window.execScript(sc);
             } 	else  {
                window.setTimeout(sc,0);
             }
        }
    );
	return true;
}

/**
* Map array elements
* @param {Function} fun
* @return Function
**************************** 
*  Considerant x un array.
*  x.map(nomFuncio);
*  Aplica a tots els elements de l'array el tractament nomFuncio().
*/
Array.prototype.map = function(fun) {
	if(typeof fun!=="function"){return false;}
	var i = 0, l = this.length;
	for(i=0; i<l; i++) {
		fun(this[i]);
	}
	return true;
}

